import { Injectable } from '@nestjs/common';
import { MysqlService } from '../../database/mysql/mysql.service';
import { BusinessException } from '../../types/exception/business.exception';
import { ERR_MSG } from '../../types/errcode';
import { CatDto, CatUpdateDto } from './dto/cat.dto';

@Injectable()
export class CatService {
  constructor(private readonly _mysqlService: MysqlService) {}

  // 创建猫
  async create(cat: CatDto) {
    const newCat = this._mysqlService.catRepository.create(cat);
    await this._mysqlService.catRepository.save(newCat);
    return { msg: '创建成功' };
  }

  // 查询所有猫
  async findAll() {
    const [list, total] = await this._mysqlService.catRepository.findAndCount();
    return { list, total };
  }

  // 更新猫
  async update(cat: CatUpdateDto) {
    if (!cat.id) {
      throw new BusinessException(ERR_MSG.CUSTOM, 'id不能为空');
    }

    // 判断当前id是否存在（使用 findOne 正确查询）
    const existingCat = await this._mysqlService.catRepository.findOneBy({
      id: cat.id,
    });
    if (!existingCat) {
      throw new BusinessException(ERR_MSG.CUSTOM, 'id不存在');
    }

    await this._mysqlService.catRepository.update(cat.id, cat);
    return { msg: '更新成功' };
  }
}
